<template lang="pug">
data-page(
  v-bind="pageParams"
)
  mt-table(
    v-bind="tableProps"
  )
  batchList(v-model="batchListShow" :batchNumber = "batchNumber" :state = "states" @message-to-parent="request('tableData')")
  printReport(:select-item="selectRow")

  </template>

<script setup lang="ts">
import {
  type FormItemProps,
  type IAction,
  type DataPageProps,
  type Action,
  type TableProps,
  useNotify,
  Icon,
} from "@scmt/common-components";
import { useRequest } from "@scmt/common-hooks";
import { type QueryPagination, useApi } from "@scmt/core-api";
import type {
  InspectionAgencyEntity,
  InspectionAgencyQueryParams,
} from "@scmt/api-lis-inspection-agency";
import batchList from "./batchList.vue";
import printReport from "./print-report.vue";
import { useUtils } from "@scmt/lib-utils";

const $api = useApi();
const $utils = useUtils();
const $notify = useNotify();
const queryPramas = reactive<InspectionAgencyQueryParams>({
  outward: 1,
  pageNum: 1,
  pageSize: 20,
});
const editingObj = ref<null | InspectionAgencyEntity>(null);
const batchListShow = ref(false);
const batchNumber = ref("");
const states = ref(null);
const selectRow = ref({});

const { request, data, loadingMap } = useRequest({
  tableData: (q: any) => {
    const params = Object.assign({}, queryPramas, q);
    return $api.lis.inspectionAgency.query(params);
  },
  save: (model: InspectionAgencyEntity) => {
    return $api.lis.inspectionAgency.save(model).then(() => {
      $notify.success("保存成功");
      editingObj.value = null;

      request("tableData", {
        pageSize: 20,
      });
    });
  },
  destroy: (ids: string) => {
    return $api.lis.inspectionAgency.destroy(ids).then(() => {
      $notify.success("删除成功");

      request("tableData", {
        pageSize: 20,
      });
    });
  },
  listDoctorAsOptions: (val: string) =>
    $api.user.listDoctorAsOptions({ officeId: val }),
  getAll: (q: any) => {
    return $api.lis.specimen.getAll(q);
  },
});

onMounted(() => {
  request("tableData");
  request("listDoctorAsOptions");
});

//初始化打印需要的值
const initPrintModel = (val: string, list: []) => {
  selectRow.value = {};
  setTimeout(() => {
    let numbers = list.map((item) => {
      return item.barcode.substring(11, 14);
    });
    let minNumber = Math.max(...numbers);
    let maxNumber = Math.min(...numbers);
    selectRow.value = {
      id: "cb2bd1b5b6552fc31faba632e7cd7a59",
      batchNumber: val,
      person: minNumber + "-" + maxNumber,
      number: list.length,
      sendInspectionTime: $utils.formatDate(Date.now(), "YYYY-MM-DD HH:mm:ss"),
      data: list,
    };
  }, 500);
};

const pageParams = computed<DataPageProps>(() => {
  const queryFields: FormItemProps[] = [
    {
      prop: "batchNumber",
      label: "批次号",
    },
    {
      prop: "generationTime",
      label: "送检时间",
      as: "date",
    },
  ];
  const headerActions: Action[] = [
    {
      label: "新增批次",
      event: "sampleSubmission",
      type: "primary",
    },
  ];

  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    queryFields,
    actions: headerActions,
    onQuery: () => request("tableData"),
    onAct: onPageActions,
    alignAction: "right",
  };

  return dataPageProps;
});

const tableProps = computed(() => {
  const { tableData } = toRefs(data);

  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    columns: [
      {
        type: "selection",
        label: "序号",
        width: "60px",
      },
      {
        prop: "batchNumber",
        label: "批次号",
        tooltip: true,
      },

      {
        prop: "state",
        label: "批次状态",
        tooltip: true,
        sortable: true,
        render: ({ row }) => {
          let iconName = "";
          let content = "";
          let color = "";
          switch (row.state) {
            case 1: {
              iconName = "Promotion";
              content = "已送检";
              color = "orange";
              break;
            }
            case 2: {
              iconName = "Memo";
              content = "已签收";
              color = "green";
              break;
            }
          }
          return h(
            "div",
            {
              style: {
                display: "flex",
                alignItems: "center",
              },
            },
            [
              h(Icon, {
                name: iconName,
                style: {
                  color: color,
                },
              }),
              h(
                "span",
                {
                  style: {
                    marginLeft: "var(--mt-margin-small)",
                  },
                },
                content
              ),
            ]
          );
        },
      },
      {
        prop: "specimenType",
        label: "标本类型",
        tooltip: true,
      },
      {
        prop: "numberPeople",
        label: "样品数量",
        tooltip: true,
      },
      {
        prop: "sendInspectionId",
        label: "送检人",
        tooltip: true,
        render: ({ row }) => {
          const patientType = data.listDoctorAsOptions ?? [];
          let resText = row.sendInspectionId + "";
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.sendInspectionId
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      {
        prop: "generationTime",
        label: "送检时间",
        tooltip: true,
        sortable: true,
      },
      {
        prop: "outwardOrgName",
        label: "送检机构",
        tooltip: true,
      },
      {
        prop: "outward",
        label: "是否外送",
        tooltip: true,
        sortable: true,
        width: 130,
        render: ({ row }) => {
          if (row.outward == 1) {
            return h("div", "是");
          } else {
            return h("div", "否");
          }
        },
      },
      {
        label: "操作",
        fixed: "right",
        actions: [
          {
            label: "送检明细",
            event: "detailed",
            type: "primary",
          },
          {
            label: "打印送检单",
            event: "print",
            type: "primary",
          },
        ],
      },
    ],
    onAct: onPageActions,
    onPaginate: (pagination: QueryPagination) =>
      request("tableData", pagination),
    highlightCurrentRow: true,
  };
  return tableProps;
});

const onPageActions = (action: IAction, model?: any) => {
  switch (action.event) {
    case "add":
    case "edit":
      editingObj.value = $api.lis.inspectionAgency.$$createEntity(model);
      break;
    case "destroy":
      request("destroy", model ? model.id : "");
      break;
    case "detailed":
      states.value = null;
      batchNumber.value = "";
      batchNumber.value = model.batchNumber;
      batchListShow.value = true;
      break;
    case "sampleSubmission":
      states.value = 4;
      batchNumber.value = "null";
      batchListShow.value = true;
      break;
    case "print":
      request("getAll", { batchNumber: model.batchNumber }).then((res) => {
        if (res) {
          initPrintModel(model, res);
        }
      });
      break;
  }
};
</script>

<style lang="less" scoped></style>
